<template>
  <div class="updatePasswordContainer">
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
      status-icon
    >
      <el-form-item label="新密码" prop="newPwd">
        <el-input
          type="password"
          v-model="ruleForm.newPwd"
          show-password
          clearable
        />
      </el-form-item>
      <el-form-item label="确认新密码" prop="ensureNewPwd">
        <el-input
          type="password"
          v-model="ruleForm.ensureNewPwd"
          show-password
          clearable
        />
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch } from "vue";
import type { FormInstance, FormRules } from "element-plus";
// utils
import { checkPassword } from "@/utils/util";
// store
import useForgetPwd from "@/store/forgetPwd";

const forgetPwdStore = useForgetPwd();

interface RuleForm {
  newPwd: string;
  ensureNewPwd: string;
}

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  newPwd: "",
  ensureNewPwd: "",
});

// 自定义校验
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入新密码"));
  } else {
    if (ruleForm.ensureNewPwd !== "") {
      if (!ruleFormRef.value) return;
      ruleFormRef.value.validateField("checkPass", () => null);
    }
    // 校验密码
    if (!checkPassword(value)) {
      callback(
        new Error("密码格式错误，密码由数字、字母以及特殊字符组成且长度最少5位")
      );
    }
    callback();
  }
};
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请再次输入密码"));
  } else if (value !== ruleForm.newPwd) {
    callback(new Error("两次密码不一致"));
  } else {
    callback();
  }
};

// 校验规则
const rules = reactive<FormRules<RuleForm>>({
  newPwd: [{ validator: validatePass, required: true, trigger: "blur" }],
  ensureNewPwd: [{ validator: validatePass2, required: true, trigger: "blur" }],
});

watch(
  () => ruleForm,
  () => {
    // 如果两个密码都有值且值相同的时候 就存入store
    // if (ruleForm.newPwd && ruleForm.ensureNewPwd) {
    //   forgetPwdStore.setNewPwd(ruleForm.newPwd, ruleForm.ensureNewPwd);
    // }
    forgetPwdStore.setNewPwd(ruleForm.newPwd, ruleForm.ensureNewPwd);
  },
  { deep: true }
);
</script>

<style scoped lang="scss">
.updatePasswordContainer {
  // border: 1px solid red;
  width: 50%;
  margin: 20px auto;
  padding: 30px;
  .el-form-item {
    margin: 20px 0;
  }
}
</style>
